//
//  schoolView.m
//  QingTengGaoXiao
//
//  Created by 沈煜航 on 2018/10/3.
//  Copyright © 2018年 QingTeng. All rights reserved.
//

#import "schoolView.h"
#import "DataModel.h"

@interface schoolView() <UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate>

//存放搜索结果的数组
@property (nonatomic,strong) NSMutableArray *resultArray;
//存放搜索范围内的总数据
@property (nonatomic,strong) NSMutableArray *dataArray;

@end

@implementation schoolView

#pragma 重写init

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self){
        self = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:nil options:nil] objectAtIndex:0];
        [self initBeforeAll];
    }
    return self;
}

#pragma 初始化方法

-(void)initBeforeAll{
    self.schoolTable.delegate = self;
    self.schoolTable.dataSource = self;
    self.schoolSearchBar.delegate = self;
    self.schoolSearchBar.keyboardType = UIKeyboardTypeDefault;
    [self initAreaView];
    self.dataArray = [NSMutableArray array];
}

-(void)initAreaView{
    self.areaChosenView.hidden = NO;
    self.majorChosenView.hidden = YES;
    self.schoolSearchBar.placeholder = @"搜索地区";
    //从model载入进dataArray
    
    
    self.resultArray = self.dataArray;
    
}

-(void)initMajorView{
    self.areaChosenView.hidden = YES;
    self.majorChosenView.hidden = NO;
    self.schoolSearchBar.placeholder = @"搜索专业类";
    //从model载入进dataArray
    
    
    self.resultArray = self.dataArray;
    
}

#pragma searchBar代理实现

//搜索框内修改搜索内容时，触发下面的方法
-(BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar{
    return YES;
}

//在搜索框内开始进行关键字搜索时（点击搜索框），触发下面的方法
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    NSLog(@"开始输入");
    //出现取消按钮
    [searchBar setShowsCancelButton:YES animated:YES];
    //改变取消按钮的文本内容
    for(UIView* view in searchBar.subviews.firstObject.subviews){
        if([view isKindOfClass:[UIButton class]]){
            UIButton* cancelButton = (UIButton*) view;
            [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
        }
    }
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    NSLog(@"输入完毕，开始搜索");
}

//搜索框中关键字变化时的事件响应
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    NSLog(@"输入的关键字是---%@---%lu",searchText,(unsigned long)searchText.length);
    //清空存放搜索结果的数组
    [self.resultArray removeAllObjects];
    searchText = [self transformToPinyin:searchText];
    //加多线程，以免卡顿
    dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
    dispatch_async(globalQueue, ^{
        if(searchText != nil && searchText.length > 0){
            //遍历需要搜索的所有内容，dataArray存放总数据
            for(DataModel* model in self.dataArray){
                NSString* tempString = model.content;
                //把所有的搜索结果转成拼音
                NSString* pinyinString = [self transformToPinyin:tempString];
                NSLog(@"转为拼音---%@",pinyinString);
                
                if([pinyinString rangeOfString:searchText options:NSCaseInsensitiveSearch].length > 0){
                    [self.resultArray addObject:model];
                }
            }
        }
        else{
            self.resultArray = [NSMutableArray arrayWithArray:self.dataArray];
        }
        //回到主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.schoolTable reloadData];
        });
    });
}

//按下取消键时关闭键盘输入并让取消键消失
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [searchBar setShowsCancelButton:NO animated:YES];
    [searchBar endEditing:YES];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [searchBar setShowsCancelButton:NO animated:YES];
    [searchBar endEditing:YES];
}

#pragma tableView代理实现

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.resultArray.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"1"];
    if(cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"1"];
    }
    //赋值内容
    
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //num存当前点击的cell的行号
    NSInteger num = indexPath.row;
    //根据行号从resultArray里取出对应的model
    DataModel* model = [self.resultArray objectAtIndex:num];
    //通过model打开对应的窗口
    
    
}

#pragma 功能性方法

//汉字转拼音
-(NSString*)transformToPinyin:(NSString*)aString{
    //转成可变字符串
    NSMutableString* str = [NSMutableString stringWithString:aString];
    //汉字转拼音（带声调）
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);
    //转为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
    
    return str;
}

-(NSMutableArray*)resultArray{
    if(_resultArray == nil){
        _resultArray = [NSMutableArray arrayWithArray:self.dataArray];
    }
    return _resultArray;
}

#pragma public方法

-(void)changeTitle{
    UIView* rootView = self.superview.superview;
    for(UIView* view in rootView.subviews){
        if(view.tag == 123){
            rootView = view;
            break;
        }
    }
    for(UIView* view in rootView.subviews){
        if(view.tag == 123){
            UILabel* titleLabel = (UILabel*)view;
            [titleLabel setText:@"总览"];
            break;
        }
    }
}

#pragma 按钮的action

- (IBAction)headButtonsAction:(UIButton *)sender {
    switch (sender.tag) {
        case 1:
            [self initAreaView];
            break;
        case 2:
            [self initMajorView];
            break;
        default:
            break;
    }
}

@end
